/**
 * @param {string} queryIP
 * @return {string}
 */
export var validIPAddress = function (queryIP) {
  if (isIPv4(queryIP)) return 'IPv4'
  if (isIPv6(queryIP)) return 'IPv6'
  return 'Neither'
}

function isIPv4(queryIP) {
  const ipArray = queryIP.split('.')
  if (ipArray.length !== 4) return false
  for (let i = 0; i < ipArray.length; i++) {
    const num = Number(ipArray[i])
    if (num < 0 || num > 255 || isNaN(num)) return false
    if (String(num) !== ipArray[i]) return false
  }
  return true
}

function isIPv6(queryIP) {
  const ipArray = queryIP.split(':')
  if (ipArray.length !== 8) return false
  for (let i = 0; i < ipArray.length; i++) {
    if (ipArray[i].length === 0) return false
    if (ipArray[i].length > 4) return false
    const num = Number('0x' + ipArray[i])
    if (num < 0 || num > 65535 || isNaN(num)) return false
  }
  return true
}

/**
 * 正则
 * @param {string} queryIP
 * @return {string}
 */
export var validIPAddress2 = function (IP) {
  const arr4 = IP.split('.')
  const arr6 = IP.split(':')
  if (arr4.length === 4) {
    if (arr4.every(part => part.match(/^0$|^([1-9]\d{0,2})$/) && part < 256)) {
      return 'IPv4'
    }
  } else if (arr6.length === 8) {
    if (arr6.every(part => part.match(/^[0-9a-fA-F]{1,4}$/))) {
      return 'IPv6'
    }
  }
  return 'Neither'
}
